<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          plain
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:user:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
        >删除
        </el-button
        >
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:post:export']"-->
      <!--        >导出-->
      <!--        </el-button-->
      <!--        >-->
      <!--      </el-col>-->
      <!--      <right-toolbar-->
      <!--        :showSearch.sync="showSearch"-->
      <!--        @queryTable="getList"-->
      <!--      ></right-toolbar>-->
    </el-row>
    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="头像" align="center" width="100">
        <template slot-scope="scope">
          <ImagePreview :src="scope.row.avatar" :width="50" :height="50"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="nickName"/>
      <el-table-column label="联系电话" align="center" prop="phonenumber"/>
      <el-table-column label="所属组织" align="center">
        <template slot-scope="scope">
          {{ scope.row.dept ? scope.row.dept.deptName : '' }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="身份类型" align="center" prop="isSecurity">-->
      <!--        <template slot-scope="scope">-->
      <!--          {{ commonData.user_type[scope.row.type - 1].label }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="保安" align="center" prop="isSecurity">-->
      <!--        <template slot-scope="scope">-->
      <!--          {{ scope.row.isSecurity ? '是' : '否' }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.status == '1'">离职</el-tag>
          <el-tag type="success" v-else>在职</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdateList(scope.row)"-->
          <!--            v-hasPermi="['system:user:edit']"-->
          <!--          >转为保安-->
          <!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:user:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
          >删除
          </el-button
          >
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                       v-hasPermi="['system:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleUpdateList" icon="el-icon-circle-check"
                                v-hasPermi="['system:user:edit']">转为保安
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status==0" command="handleViewTeam" icon="el-icon-folder-delete"
                                v-hasPermi="['system:user:edit']">离职
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body class="my-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="所属组织" prop="isEmpty">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属组织"
                          size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择身份类型">
                <el-option
                  v-for="item in commonData.user_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex">
                <el-option
                  v-for="item in dict.type.sys_user_sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idNumber">
              <el-input v-model="form.idNumber" placeholder="请输入身份证"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限角色" prop="isEmpty">
              <el-select v-model="form.roleId">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="是否是保安" prop="isSecurity">-->
          <!--              <el-radio-group v-model="form.isSecurity">-->
          <!--                <el-radio-->
          <!--                  v-for="dict in commonData.yes_no"-->
          <!--                  :key="dict.value"-->
          <!--                  :label="dict.value"-->
          <!--                >{{dict.label}}</el-radio>-->
          <!--              </el-radio-group>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="头像" prop="avatar">
              <image-upload v-model="form.avatar" :limit="1" :isShowTip="false"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listUser, getUser, addUser, updateUser, delUser, deptTreeSelect, updateUserEdit} from '@/api/system/user'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import commonData from "@/utils/commonData"
import {listRoleOne} from "@/api/system/role";

export default {
  name: "Post",
  dicts: ['sys_user_sex', 'sys_normal_disable'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        phonenumber: undefined,
        isSecurity: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ],
        sex: [
          {required: true, message: "性别不能为空", trigger: "blur"}
        ],
        phonenumber: [
          {required: true, message: "联系电话不能为空", trigger: "blur"}
        ],
        isEmpty: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "身份类型不能为空", trigger: "blur"}
        ]
      },
      commonData: commonData,
      roleList: [],
      activeName: 'user'
    };
  },
  created() {
    this.getList();
    this.getDeptTree()
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined, //组织id
        userName: '', //用户名/账号
        nickName: '', // 姓名
        type: '', //类型
        phonenumber: '', //电话
        sex: '0', //性别
        avatar: '', //头像
        idNumber: '', //身份证
        status: 0, //帐号状态（0正常 1停用）
        isSecurity: 0, //是否保安
        isEmpty: 1
      };
      this.cascaderData = []
      this.resetForm("form");
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询角色列表 */
    getRoleList() {
      listRoleOne({
        pageNum: 1,
        pageSize: 50
      }).then(response => {
          let list_ = []
          for (let item of response.rows) {
            if (item.roleName !== '保安') {
              list_.push(item)
            }
          }
          this.roleList = list_;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // getUser().then(response => {
      //   this.postOptions = response.posts;
      //   this.roleOptions = response.roles;
      //   this.open = true;
      //   this.title = "添加用户";
      //   this.form.password = this.initPassword;
      // });
      this.reset();
      this.getRoleList()

      this.open = true;
      this.title = "添加人员信息";
    },
    handleUpdateList(row) {
      this.$modal.confirm('确认要将该用户转为保安账号吗？').then(function () {
        return updateUserEdit({userId: row.userId, isSecurity: 1, userName: row.userName});
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("操作成功");
      }).catch(function () {
      });
    },
    handleViewTeam(row) {
      // this.$message.error('功能开发中')
      this.$modal.confirm('确认该保安离职，是否继续？').then(function () {
        return updateUserEdit({userId: row.userId, status: 1, userName: row.userName});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
        console.log('信息')
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.userId || this.ids
      this.getRoleList()
      getUser(postId).then(response => {
        console.log('response:', response)
        delete response.data.dept
        this.form = response.data;
        this.form.roleId = response.roleIds[0]
        this.form.isEmpty = 1
        this.open = true;
        this.title = "修改人员信息";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data_ = this.$deepCopy(this.form)
          data_.userName = data_.phonenumber
          data_.roleIds = [data_.roleId]
          if (!data_.deptId) {
            this.$modal.msgError('所属组织不能为空');
            return
          }
          delete data_.isEmpty
          if (data_.userId != undefined) {
            updateUser(data_).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            data_.password = '123456'
            data_.rawPassword = '123456'
            addUser(data_).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.nickName + '"客户吗？').then(function () {
        return updateUser({userId: row.userId, status: row.status});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除"' + row.nickName + '"的数据项？').then(function () {
        return delUser(postIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdateList":
          this.handleUpdateList(row);
          break;
        case "handleViewTeam":
          this.handleViewTeam(row);
          break;
        default:
          break;
      }
    },
  }
};
</script>
